<template>
  <div class="comments-container">
    <h2>评论管理</h2>
    
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="评论内容">
          <el-input v-model="searchForm.contentFuzzy" placeholder="请输入评论内容" clearable />
        </el-form-item>
        <el-form-item label="活动">
          <el-select v-model="searchForm.activityId" placeholder="请选择活动" clearable style="width: 200px;">
            <el-option
              v-for="activity in activityList"
              :key="activity.id"
              :label="activity.title"
              :value="activity.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="新闻">
          <el-select v-model="searchForm.newsId" placeholder="请选择新闻" clearable style="width: 200px;">
            <el-option
              v-for="news in newsList"
              :key="news.id"
              :label="news.title"
              :value="news.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评论人">
          <el-input v-model="searchForm.userName" placeholder="请输入评论人" clearable />
        </el-form-item>
        <el-form-item label="评论时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="点赞量区间">
          <el-input-number v-model="searchForm.likeCountMin" :min="0" placeholder="最小点赞量" clearable />
          <span style="margin: 0 10px;">至</span>
          <el-input-number v-model="searchForm.likeCountMax" :min="0" placeholder="最大点赞量" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 200px;">
            <el-option label="隐藏" :value="0" />
            <el-option label="展示" :value="1" />
            <el-option label="精选" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 评论列表 -->
    <el-table :data="commentList" border style="width: 100%" v-loading="commentLoading">
      <el-table-column prop="content" label="评论内容" />
      <el-table-column prop="activityTitle" label="所属活动" />
      <el-table-column prop="createTime" label="评论时间" :formatter="formatDateTime" />
      <el-table-column prop="userName" label="评论人" />
      <el-table-column prop="likeCount" label="点赞量" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-select v-model="scope.row.status" @change="handleStatusChange(scope.row)">
            <el-option label="隐藏" :value="0" />
            <el-option label="展示" :value="1" />
            <el-option label="精选" :value="2" />
          </el-select>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// 列表数据
const commentList = ref([])
const commentLoading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const activityList = ref([])

// 新增新闻列表
const newsList = ref([])

// 加载新闻列表
const loadNews = async () => {
  try {
    const res = await axios.get('/news/loadDataList') // 假设新闻列表的请求路径
    if (res.data.status === 'success') {
      newsList.value = res.data.data.list
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
  }
}

// 搜索表单
const searchForm = reactive({
  contentFuzzy: '',
  activityId: '',
  userName: '',
  createdAtStart: '',
  createdAtEnd: '',
  likeCountMin: null,
  likeCountMax: null
})

// 日期范围
const dateRange = ref([])

// 处理日期变化
const handleDateChange = (val) => {
  if (val) {
    searchForm.createdAtStart = val[0]
    searchForm.createdAtEnd = val[1]
  } else {
    searchForm.createdAtStart = ''
    searchForm.createdAtEnd = ''
  }
}

// 加载评论列表
const loadComments = async () => {
  commentLoading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }

    const res = await axios.get('/comment/admin/loadDataList', { params })
    if (res.data.status === 'success') {
      commentList.value = res.data.data.list.map(comment => ({
        id: comment.id,
        content: comment.content,
        activityTitle: comment.commented,
        createTime: comment.createdAt,
        visible: comment.status === 1,
        status: comment.status,
        likeCount: comment.likeCount,
        userName: comment.userName
      }))
      total.value = res.data.data.totalCount
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    commentLoading.value = false
  }
}

// 加载活动列表
const loadActivities = async () => {
  try {
    const res = await axios.get('/activity/loadDataList') // 修改请求路径
    if (res.data.status === 'success') {
      activityList.value = res.data.data.list
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
  }
}

const getStatusType = (status) => {
  const types = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    0: '隐藏',
    1: '展示',
    2: '精选'
  }
  return texts[status] || '未知'
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadComments()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  dateRange.value = []
  currentPage.value = 1
  loadComments()
}

// 处理状态变化
const handleStatusChange = async (row) => {
  try {
    await axios.post('/comment/updateCommentById', {
      id: row.id,
      status: row.status
    })
    ElMessage.success('操作成功')
    // 更新 commentList 中对应评论的状态
    const updatedCommentIndex = commentList.value.findIndex(comment => comment.id === row.id)
    if (updatedCommentIndex !== -1) {
      commentList.value[updatedCommentIndex].status = row.status
    }
    // 重新加载数据以确保表格显示最新的状态
    // loadComments()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
    // 恢复原始状态
    row.status = row.status === 0 ? 1 : 0
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadComments()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadComments()
}

// 格式化时间
const formatDateTime = (row, column) => {
  return row[column.property] ? dayjs(row[column.property]).format('YYYY-MM-DD HH:mm:ss') : ''
}

onMounted(() => {
  loadComments()
  loadActivities()
  loadNews() // 加载新闻列表
})
</script>

<style scoped>
.comments-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  z-index: 1;
  position: relative;
}

:deep(.el-pagination) {
  margin: 0;
  padding: 0;
}
</style>